//
//  WordsConfigVC.swift
//  Game
//
//  Created by woniu on 2025/9/4.
//配置单词列表

import UIKit
import SnapKit

class WordsConfigVC: UIViewController {
    public var gameModel:GameModel!
    public var onSubmitBlock: (()->())?
    
    private let nameField = UITextField()
	private var tableView: UITableView!
	private var addButton: UIButton!
	private var saveButton: UIButton!

	private var configModel = FindeWordConfig()

	override func viewDidLoad() {
		super.viewDidLoad()
        view.backgroundColor = .white
        self.title = "配置"
        // 返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain, target: self, action: #selector(onBack))
        navigationController?.navigationBar.tintColor = Colors.title
        if gameModel == nil{
            gameModel = GameModel.defaultFindWordModel()
        }
        let dic = gameModel.jsonData.toDic()
        configModel = FindeWordConfig.deserialize(from: dic) ?? FindeWordConfig()
		setupUI()
	}
    
    @objc private func onBack() {
        if let nav = navigationController {
            nav.popViewController(animated: true)
        } else {
            dismiss(animated: true)
        }
    }

	private func setupUI() {
        
        //名称背景
        let nameCard = UIView()
        nameCard.addShadow()
        view.addSubview(nameCard)
        nameCard.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(16)
            make.left.equalToSuperview().offset(45)
            make.right.equalToSuperview().offset(-45)
            make.height.equalTo(120)
        }
        
        let nameLab = UILabel()
        nameLab.text = "名字描述"
        nameLab.font = UIFont.boldSystemFont(ofSize: 20)
        nameLab.textColor = Colors.title
        nameCard.addSubview(nameLab)
        nameLab.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(15)
        }
        
        nameField.placeholder = "添加名字、描述"
        nameField.text = gameModel.name
        nameField.leftViewMode = .always
        nameField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: 40))
        nameField.rightViewMode = .always
        nameField.clearButtonMode = .unlessEditing
        nameField.textColor = .black
        nameField.circular(28)
        nameField.borderSet(Colors.blue.withAlphaComponent(0.4), 2)
        nameField.font = UIFont.systemFont(ofSize: 17)
        nameCard.addSubview(nameField)
        nameField.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(8)
            make.right.equalToSuperview().offset(-8)
            make.top.equalTo(nameLab.snp.bottom).offset(10)
            make.height.equalTo(56)
        }
        
        
		tableView = UITableView(frame: .zero, style: .plain)
		tableView.register(InputRowCell.self, forCellReuseIdentifier: InputRowCell.reuseId)
		tableView.dataSource = self
		tableView.delegate = self
		tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
		tableView.rowHeight = 70
		view.addSubview(tableView)

		addButton = UIButton(type: .system)
		addButton.setTitle("添加一行", for: .normal)
		addButton.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
		addButton.backgroundColor = Colors.blue
		addButton.setTitleColor(.white, for: .normal)
		addButton.layer.cornerRadius = 10
		addButton.addTarget(self, action: #selector(onAddRow), for: .touchUpInside)
		view.addSubview(addButton)

		saveButton = UIButton(type: .system)
		saveButton.setTitle("保存并关闭", for: .normal)
		saveButton.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
		saveButton.backgroundColor = Colors.green
		saveButton.setTitleColor(.white, for: .normal)
		saveButton.layer.cornerRadius = 10
		saveButton.addTarget(self, action: #selector(onSave), for: .touchUpInside)
		view.addSubview(saveButton)

		// 布局 (针对 iPad 风格，留白较多)
		tableView.snp.makeConstraints { make in
            make.top.equalTo(nameCard.snp.bottom).offset(15)
			make.left.equalToSuperview().offset(40)
			make.right.equalToSuperview().offset(-40)
			make.bottom.equalTo(addButton.snp.top).offset(-20)
		}

		addButton.snp.makeConstraints { make in
			make.left.equalTo(tableView)
			make.height.equalTo(50)
			make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-20)
			make.width.equalTo(160)
		}

		saveButton.snp.makeConstraints { make in
			make.right.equalTo(tableView)
			make.height.equalTo(50)
			make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-20)
			make.width.equalTo(160)
		}
	}

	@objc private func onAddRow() {
		configModel.inputContentList.append("")
		tableView.reloadData()
		// 滚动到最后一行
		let last = configModel.inputContentList.count - 1
		if last >= 0 {
			tableView.scrollToRow(at: IndexPath(row: last, section: 0), at: .bottom, animated: true)
		}
	}

	@objc private func onSave() {
        let name = nameField.text ?? ""
        if name.isEmpty{
            Utils.alert(msg: "请输入名称、描述")
            return
        }
        gameModel.name = name
		// 打印不为空的元素
		let nonEmpty = configModel.inputContentList.filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
        if nonEmpty.isEmpty{
            Utils.alert(msg: "请填入信息再提交")
            return
        }
        configModel.inputContentList = nonEmpty
        gameModel.jsonData = configModel.toJSONString() ?? ""
        
		print("保存的数据:\(gameModel.toJSONString() ?? "")")
        GameManager.share.insertOrUpdate(game: gameModel)
        onSubmitBlock?()
        self.navigationController?.popViewController(animated: true)
	}
}

extension WordsConfigVC: UITableViewDataSource, UITableViewDelegate {
    
	func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return configModel.inputContentList.count
	}

	func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
		let cell = tableView.dequeueReusableCell(withIdentifier: InputRowCell.reuseId, for: indexPath) as! InputRowCell
		let idx = indexPath.row + 1
		let text = configModel.inputContentList[indexPath.row]
		cell.configure(index: idx, text: text)
		cell.onTextChange = {[weak self] newText in
			guard let `self` = self else { return }
			self.configModel.inputContentList[indexPath.row] = newText
		}
		return cell
	}

	func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
		tableView.deselectRow(at: indexPath, animated: true)
	}
}
